package pers.cj.pdos.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.*;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.service.*;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.*;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/goods")
public class GoodsController extends BaseController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsStockService goodsStockService;
    @Autowired
    private IPacketGoodsService packetGoodsService;
    @Autowired
    IGoodsSnService goodsSnService;
    @Autowired
    private ITypeService typeService;
    @Autowired
    private IGoodsUnitService goodsUnitService;
    @Autowired
    IHouseService houseService;
    @Autowired
    IAttrNameService attrNameService;

    @RequiresPermissions("goods:query")
    @RequestMapping("/goods")
    public String goods(Model model) {
        IndustryType industryType = getIndustryType();
        model.addAttribute(industryType);
        return "goods/goods";
    }

    @RequiresPermissions("goods:insert")
    @RequestMapping("/goodsNew")
    public String goodsNew(Model model) {
        model.addAttribute(getIndustryType());

        //由后端生成商品id给到前端使用
        String id = UuidUtils.getUUID();
        model.addAttribute("id", id);

        Company company = getCompany();
        model.addAttribute("houseVoList", houseService.listNormalVo(company.getId(), PdosUtils.getViewHouseStoreId(getLoginUserVo(), null)));
        model.addAttribute("attrNameVoList", attrNameService.listVo(company.getId()));
        return "goods/goodsNew";
    }

    @RequiresPermissions("goods:insert")
    @RequestMapping("/goodsEdit")
    public String goodsEdit(Model model, String id) {
        Company company = getCompany();
        model.addAttribute(getIndustryType());
        model.addAttribute("id", id);

        model.addAttribute("houseVoList", houseService.listNormalVo(company.getId(), PdosUtils.getViewHouseStoreId(getLoginUserVo(), null)));
        model.addAttribute("attrNameVoList", attrNameService.listVo(company.getId()));

        model.addAttribute("totalStock",goodsStockService.countByGoods(id));
        model.addAttribute("used",goodsService.check(id));//是否单据引用

        Goods goods = new Goods();
        goods.setId(id);
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(goods);
        model.addAttribute("usedByPacket", packetGoodsService.checkByGoodsList(goodsList));
        return "goods/goodsEdit";
    }

    @RequiresPermissions("goods:query")
    @RequestMapping("/goodsDetail")
    public String goodsDetail(Model model, String id) {
        Company company = getCompany();
        model.addAttribute("id",id);
        model.addAttribute(getIndustryType());
        model.addAttribute("houseVoList", houseService.listNormalVo(company.getId(), PdosUtils.getViewHouseStoreId(getLoginUserVo(), null)));
        return "goods/goodsDetail";
    }

    @RequiresPermissions("goods:insert")
    @RequestMapping("/goodsQuickPrice")
    public String goodsQuickPrice() {
        return "goods/goodsQuickPrice";
    }

    @ResponseBody
    @RequestMapping("/goods/listVoForCheckHouse")
    public ResponseList listVoForCheckHouse(int page,
                                         int limit,
                                         String status,
                                         String search,
                                         String typeId,
                                         String no,
                                         String name,
                                         String attr,
                                         String norms,
                                         String remark,
                                         String sn,
                                         String houseId) {
        Company company = getCompany();
        List<GoodsVo> list = goodsService.listVoForCheckHouse(company.getId(),
                page,
                limit,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn),
                houseId);
        long total = goodsService.count(company.getId(),
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn));
        return ResponseList.success(total,list);
    }

    @ResponseBody
    @RequestMapping("/goods/getListWithStock")
    public ResponseList getListWithStock(int page,
                                int limit,
                                String status,
                                String search,
                                String typeId,
                                String no,
                                String name,
                                String attr,
                                String norms,
                                String remark,
                                String sn,
                                String houseId) {
        Company company = getCompany();
        List<GoodsVo> list = goodsService.listVoWithStockPage(company.getId(),
                page,
                limit,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn),
                houseId);
        long total = goodsService.count(company.getId(),
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn));
        return ResponseList.success(total,list);
    }

    @ResponseBody
    @RequestMapping("/goods/getList")
    public ResponseList getList(int page,
                                int limit,
                                String status,
                                String search,
                                String typeId,
                                String no,
                                String name,
                                String attr,
                                String norms,
                                String remark,
                                String sn) {
        Company company = getCompany();
        List<GoodsVo> list = goodsService.listVoPage(company.getId(),
                page,
                limit,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn));
        long total = goodsService.count(company.getId(),
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn));
        return ResponseList.success(total,list);
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/insert")
    public ResponseEntity insert(@RequestBody GoodsVo goodsVo) {
        Company company = getCompany();

        //防止前端生成的商品编号有问题
        if (goodsService.checkNo(company.getId(), goodsVo.getId(),goodsVo.getNo())){
            return ResponseEntity.fail("商品编号重复");
        }

        if (goodsService.checkName(company.getId(), goodsVo.getId(),goodsVo.getName())){
            return ResponseEntity.fail("商品编号重复");
        }



        List<GoodsUnit> goodsUnitList = goodsVo.getGoodsUnitList();
        if (!Utils.isEmpty(goodsUnitList)) {
            //先检查前台传过来的是否正确
            ResponseEntity responseEntity = checkUploadUnit(company, goodsVo);
            if (responseEntity != null) {
                return responseEntity;
            }
        }

        Goods goods = DataUtil.genEntityFromVo(Goods.class, goodsVo);
        DataUtil.processEntity(false,company, goods);
        if (goods.getSn() == null) {
            goods.setSn(false);
        }

        List<GoodsAttr> goodsAttrList = goodsVo.getGoodsAttrList();
        List<GoodsInit> goodsInitList = goodsVo.getGoodsInitList();
        DataUtil.processList(company, goodsInitList);
        DataUtil.processList(company, goodsAttrList);
        DataUtil.processList(company, goodsUnitList);

        List<GoodsSn> goodsSnList = new ArrayList<>();
        List<GoodsSnLog> goodsSnLogList = new ArrayList<>();
        if (!goods.getSn()){
            goodsSnList = null;
        } else {
            for (GoodsSn goodsSn:goodsVo.getInitGoodsSnList()){
                DataUtil.processEntity(company, goodsSn);
                goodsSn.setStatus(1);
                goodsSn.setInDate(new Date());
                goodsSnList.add(goodsSn);

                GoodsSnLog goodsSnLog = new GoodsSnLog();
                DataUtil.processEntity(company, goodsSnLog);
                goodsSnLog.setGoodsId(goodsSn.getGoodsId());
                goodsSnLog.setSn(goodsSn.getSn());
                goodsSnLog.setType(17);
                goodsSnLogList.add(goodsSnLog);
            }
        }


        List<GoodsHouseWarn> goodsHouseWarnList = goodsVo.getGoodsHouseWarnList();
        DataUtil.processList(company, goodsHouseWarnList);

        try {
            goodsService.save(goods,goodsAttrList,goodsUnitList,goodsHouseWarnList, goodsInitList, goodsSnList, goodsSnLogList);
            return ResponseEntity.success();
        } catch (Exception e){
            return ResponseEntity.fail("新增商品失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/update")
    public ResponseEntity update(@RequestBody GoodsVo goodsVo) {
        Company company = getCompany();
        Goods goods = DataUtil.genEntityFromVo(Goods.class, goodsVo);
        if (goods.getSn() == null) {
            goods.setSn(false);
        }
        List<GoodsUnit> goodsUnitList = goodsVo.getGoodsUnitList();

        GoodsVo db = goodsService.getVoById(goods.getId());
        boolean used = goodsService.check(goods.getId());
        //由启用到停用，检查是否被单据引用
        if (db.getStatus() == 1 && goods.getStatus() == 2 && used){
            return ResponseEntity.fail("商品被单据引用，不能停用");
        }

        //由未开启到开启sn，检查是否被单据引用
        if (!db.getSn() && goods.getSn() && used){
            return ResponseEntity.fail("商品被单据引用，不能启用序列号");
        }

        //------------------------------------------商品单位逻辑判断----------------------------------------------
        if (!Utils.isEmpty(goodsUnitList)) {
            //先检查前台传过来的是否正确
            ResponseEntity responseEntity =checkUploadUnit(company, goodsVo);
            if (responseEntity != null) {
                return responseEntity;
            }

            responseEntity =checkUnit(goods,goodsUnitList);
            if (responseEntity != null) {
                return responseEntity;
            }
        }


        DataUtil.processEntity(false,company, goods);
        Map<String,Object> map = new HashMap<>();
        map.put("goodsId", goods.getId());

        List<GoodsAttr> goodsAttrList = goodsVo.getGoodsAttrList();
        DataUtil.processList(company,goodsAttrList, map);

        DataUtil.processList(company,goodsUnitList, map);

        List<GoodsHouseWarn> goodsHouseWarnList = goodsVo.getGoodsHouseWarnList();
        DataUtil.processList(company,goodsHouseWarnList, map);

        List<GoodsInit> goodsInitList = goodsVo.getGoodsInitList();
        DataUtil.processList(company, goodsInitList);

        List<GoodsSn> goodsSnList = new ArrayList<>();
        List<GoodsSnLog> goodsSnLogList = new ArrayList<>();
        if (!goods.getSn()){
            goodsSnList = null;
            goodsSnLogList = null;
        } else {
            for (GoodsSn goodsSn:goodsVo.getInitGoodsSnList()){
                DataUtil.processEntity(company, goodsSn);
                goodsSn.setStatus(1);
                goodsSn.setInDate(new Date());
                goodsSnList.add(goodsSn);

                GoodsSnLog goodsSnLog = new GoodsSnLog();
                DataUtil.processEntity(company, goodsSnLog);
                goodsSnLog.setGoodsId(goodsSn.getGoodsId());
                goodsSnLog.setSn(goodsSn.getSn());
                goodsSnLog.setType(17);
                goodsSnLogList.add(goodsSnLog);
            }
        }

        try {
            goodsService.update(goods,goodsAttrList,goodsUnitList,goodsHouseWarnList, goodsInitList, goodsSnList, goodsSnLogList);
            return ResponseEntity.success();
        } catch (Exception e){
            return ResponseEntity.fail("更新商品失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/delete")
    public ResponseEntity delete(@RequestBody Goods goods) {
        if (goodsService.check(goods.getId())) {
            return ResponseEntity.fail("商品被单据引用，删除失败");
        }

        if(goodsStockService.checkByGoods(goods.getId())){
            return ResponseEntity.fail("商品还有库存，删除失败");
        }


        try {
            goodsService.remove(goods);
            return ResponseEntity.success();
        } catch (Exception e){
            Logger.getLogger(getClass()).error(e);
            return ResponseEntity.fail("已被使用，无法删除商品");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/batchOpenSn")
    public ResponseData batchOpenSn(@RequestBody List<Goods> goodsList) {
        if (Utils.isEmpty(goodsList)) {
            return ResponseData.success(null);
        }


        Map<String,Long> mapPacket = packetGoodsService.checkByGoodsList(goodsList);
        Map<String,Long> mapUsed = goodsService.check(goodsList);
        Map<String, GoodsUnitCountVo> mapUnit = goodsUnitService.checkByGoods(goodsList);
        List<DataMsg> noList = new ArrayList<>();
        List<Goods> list = new ArrayList<>();
        Collection<Goods> collection = goodsService.listByIds(DataUtil.genIds(goodsList));
        for (Goods goods : collection){
            if (Utils.isTrue(goods.getSn())){
                //已经开启序列号的就不需要处理了。
                continue;
            }
            if(mapUsed.containsKey(goods.getId()) && mapUsed.get(goods.getId()) > 0) {
                //当该商品的被单据引用，则从列表中剔除该商品
                noList.add(new DataMsg(goods,"该商品被业务单据引用"));
                continue;
            }
            if (mapPacket.containsKey(goods.getId()) && mapPacket.get(goods.getId()) > 0){
                noList.add(new DataMsg(goods,"该商品在某个商品套餐中"));
                continue;
            }
            if (mapUnit.containsKey(goods.getId()) && mapUnit.get(goods.getId()).isPoint()){
                noList.add(new DataMsg(goods,"该商品使用了允许小数的单位"));
                continue;
            }
            if(mapUnit.containsKey(goods.getId()) && mapUnit.get(goods.getId()).getCount()>1) {
                noList.add(new DataMsg(goods,"该商品使用了多单位"));
                continue;
            }
            list.add(goods);

        }

        ResponseData responseData;
        if (noList.size() > 0) {
            responseData = new ResponseData();
            responseData.setCode(3);
            responseData.setMsg("部分商品启用序列号失败");
            responseData.setData(noList);
        } else {
            responseData = ResponseData.success(null);
        }

        if (Utils.isEmpty(list)){
            return responseData;
        }

        try {
            DataUtil.processList(false, getCompany(),goodsList);
            goodsService.batchOpenSn(list);
            return responseData;
        } catch (Exception e){
            return responseData.fail("开启序列号失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/batchEnable")
    public ResponseEntity batchStatus(@RequestBody List<Goods> goodsList) {
        if (Utils.isEmpty(goodsList)) {
            return ResponseEntity.success();
        }
        try {
            DataUtil.processList(false, getCompany(),goodsList);
            goodsService.batchStatus(goodsList,1);
            return ResponseEntity.success();
        } catch (Exception e){
            return ResponseEntity.fail("启用商品失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/batchDisable")
    public ResponseData batchDisable(@RequestBody List<Goods> goodsList) {
        if (Utils.isEmpty(goodsList)) {
            return ResponseData.success(null);
        }


        Map<String,Long> mapPacket = packetGoodsService.checkByGoodsList(goodsList);
        Map<String,Long> mapUsed = goodsService.check(goodsList);
        List<DataMsg> noList = new ArrayList<>();
        List<Goods> list = new ArrayList<>();
        Collection<Goods> collection = goodsService.listByIds(DataUtil.genIds(goodsList));
        for (Goods goods : collection){
            if (goods.getStatus() == 2){
                //已经停用的就不需要处理了。
                continue;
            }
            if(mapUsed.containsKey(goods.getId()) && mapUsed.get(goods.getId()) > 0) {
                //当该商品的被单据引用，则从列表中剔除该商品
                noList.add(new DataMsg(goods,"该商品被业务单据引用"));
                continue;
            }
            if (mapPacket.containsKey(goods.getId()) && mapPacket.get(goods.getId()) > 0){
                noList.add(new DataMsg(goods,"该商品在某个商品套餐中"));
                continue;
            }
            list.add(goods);
        }

        ResponseData responseData;
        if (noList.size() > 0) {
            responseData = new ResponseData();
            responseData.setCode(3);
            responseData.setMsg("以下商品停用失败");
            responseData.setData(noList);
        } else {
            responseData = ResponseData.success(null);
        }

        if (Utils.isEmpty(list)){
            return responseData;
        }

        try {
            DataUtil.processList(false, getCompany(),goodsList);
            goodsService.batchStatus(list,2);
            return responseData;
        } catch (Exception e){
            return responseData.fail("停用失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/batchMoveType")
    public ResponseEntity batchMoveType(@RequestBody List<Goods> goodsList,String typeId) {
        if (Utils.isEmpty(goodsList)) {
            return ResponseEntity.success();
        }
        Company company = getCompany();
        if (Utils.isEmpty(typeId)) {
            return ResponseEntity.fail("商品分类不能为空");
        }

        if(!typeService.checkById(typeId,company.getId())) {
            return ResponseEntity.fail("商品分类不存在");
        }

        try {
            DataUtil.processList(false, company,goodsList);
            goodsService.batchMoveType(goodsList,typeId);
            return ResponseEntity.success();
        } catch (Exception e){
            return ResponseEntity.fail("更改商品分类失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/batchDelete")
    public ResponseData batchDelete(@RequestBody List<Goods> goodsList) {
        if (Utils.isEmpty(goodsList)) {
            return ResponseData.success(null);
        }

        //哪些商品还有库存
        //判断哪些商品被单据引用了
        Map<String,Long> mapUsed = goodsService.check(goodsList);
        List<DataMsg> notDeleteList = new ArrayList<>();
        List<Goods> deleteList = new ArrayList<>();
        Collection<Goods> collection = goodsService.listByIds(DataUtil.genIds(goodsList));
        for (Goods goods : collection){
            if(mapUsed.containsKey(goods.getId()) && mapUsed.get(goods.getId()) > 0) {
                //当该商品的被单据引用，则从列表中剔除该商品
                notDeleteList.add(new DataMsg(goods,"被业务单据引用"));
                continue;
            }

            deleteList.add(goods);
        }

        ResponseData responseData;
        if (notDeleteList.size() > 0) {
            responseData = new ResponseData();
            responseData.setCode(3);
            responseData.setMsg("部分商品被单据引用");
            responseData.setData(notDeleteList);
        } else {
            responseData = ResponseData.success(null);
        }

        if (Utils.isEmpty(deleteList)){
            return responseData;
        }

        try {
            DataUtil.processList(false, getCompany(),deleteList);
            goodsService.batchDelete(deleteList);
            return responseData;
        } catch (Exception e){
            return ResponseData.fail("商品被使用，删除失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("goods:insert")
    @RequestMapping("/goods/updatePrice")
    public ResponseEntity updatePrice(@RequestBody List<GoodsUnit> goodsUnitList) {
        //快捷改价
        try {
            DataUtil.processList(false, getCompany(),goodsUnitList);
            goodsUnitService.updatePrice(goodsUnitList);
            return ResponseEntity.success();
        } catch (Exception e){
            return ResponseEntity.fail("更新商品失败");
        }
    }

    @ResponseBody
    @RequestMapping("/goods/checkUse")
    public ResponseEntity checkUse(String id) {
        boolean use = goodsService.check(id);
        return use ? ResponseEntity.success() : ResponseEntity.fail("未被使用");
    }



    @ResponseBody
    @RequestMapping("/goods/findVoById")
    public ResponseData findVoById(String id) {
        GoodsVo goodsVo = goodsService.getVoById(id);
        return ResponseData.success(goodsVo);
    }

    @ResponseBody
    @RequestMapping("/goods/listVoByIds")
    public ResponseData listVoByIds(@RequestBody List<String> ids) {
        List<GoodsVo> goodsVoList = goodsService.listVoByIds(ids);
        return ResponseData.success(goodsVoList);
    }

    @ResponseBody
    @RequestMapping("/goods/getVoByCode")
    public ResponseData getVoByCode(String code) {
        try {
            GoodsVo goodsVo = goodsService.getVoByCode(code, getCompany().getId());
            if (goodsVo == null) {
                return ResponseData.fail("未找到商品");
            }
            return ResponseData.success(goodsVo);
        } catch (Exception e) {
            return ResponseData.fail("未找到商品");
        }
    }

    @ResponseBody
    @RequestMapping("/goods/beUsedByPacket")
    public ResponseData beUsedByPacket(String id) {
        boolean used = goodsService.beUsedByPacket(id);
        return ResponseData.success(used);
    }

    /**
     * 上传用户头像
     */
    @ResponseBody
    @RequestMapping(value = "/goods/uploadImg", method = RequestMethod.POST)
    public ResponseData apiUploadUserHeadImg(MultipartFile imageFile) {
        User user = getLoginUserVo();
        try {
            if(imageFile == null){
                return ResponseData.fail("图片不存在");
            }
            // 上传文件大小

            //保存头像的路径
            String path = FileProperUtil.getInstance().getVal("image.goods");
            //文件名
            String uploadName= imageFile.getOriginalFilename();
            if (Utils.isEmpty(uploadName)) {
                return ResponseData.fail("图片不存在");
            }
            String type = uploadName.substring(uploadName.lastIndexOf(".")+1);
            String filename = ImgUtil.getFileName(user.getUsername(), type);


            try{
                File dir=new File(path);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                //先把用户上传到原图保存到服务器上
                File file=new File(dir,filename);
                imageFile.transferTo(file);
                // 上传文件成功
                if(file.exists()){
                    //成功返回图片地址
                    return ResponseData.success(filename);
                }
                return ResponseData.fail("图片保存失败");
            }catch (Exception e) {
                return ResponseData.fail("图片保存失败");
            }
        }  catch (Exception e) {
            return ResponseData.fail("图片保存失败");
        }

    }


    private ResponseEntity checkUnit(Goods goods,List<GoodsUnit> goodsUnitList){
        BusinessSet businessSet = getBusinessSet();
        ResponseEntity responseEntity = null;
        GoodsVo dbGoodsVo = goodsService.getVoById(goods.getId());
        List<GoodsUnit> temp = new ArrayList<>();
        Map<String,GoodsUnitVo> tempMap = new HashMap<>();
        for (GoodsUnitVo goodsUnitVo : dbGoodsVo.getGoodsUnitVoList()) {
            temp.add(DataUtil.genEntityFromVo(GoodsUnit.class,goodsUnitVo));
            tempMap.put(goodsUnitVo.getUnitId(), goodsUnitVo);
        }

        List<CountGoodsUnitVo> countGoodsUnitVoList = goodsUnitService.checkGoodsUnitListUsed(temp);
        if (!Utils.isEmpty(countGoodsUnitVoList)){
            //不是空时才需要处理
            //1.基本单位是否改变
            if (!dbGoodsVo.getGoodsUnitVoList().get(0).getUnitId().equals(goodsUnitList.get(0).getUnitId())){
                return ResponseEntity.fail("该商品已被单据引用，基本单位《"+dbGoodsVo.getGoodsUnitVoList().get(0).getUnit().getName()+"》不能改变");
            }

            //2.取到对应的被使用的map
            Map<String,GoodsUnitVo> usedMap = new HashMap<>();
            for (CountGoodsUnitVo countGoodsUnitVo : countGoodsUnitVoList) {
                if (tempMap.containsKey(countGoodsUnitVo.getUnitId())){
                    usedMap.put(countGoodsUnitVo.getUnitId(), tempMap.get(countGoodsUnitVo.getUnitId()));
                }
            }

            Map<String,GoodsUnit> uploadMap = new HashMap<>();
            for (GoodsUnit goodsUnit : goodsUnitList) {
                uploadMap.put(goodsUnit.getUnitId(), goodsUnit);
            }

            //3. 检查是否有被删除的正在使用的单位
            responseEntity = null;
            Iterator<Map.Entry<String, GoodsUnitVo>> it = usedMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, GoodsUnitVo> entry =  it.next();
                System.out.println(entry.getKey() + " : " + entry.getValue());
                if (!uploadMap.containsKey(entry.getKey())){
                    responseEntity = ResponseEntity.fail("单位《"+entry.getValue().getUnit().getName()+"》，已被业务单据引用，不能删除");
                }
            }
            if (responseEntity != null) {
                return responseEntity;
            }

            //4.检查被使用的单位的换算倍数是否被修改
            responseEntity = null;
            for (int i=0; i < goodsUnitList.size();i++) {
                GoodsUnit goodsUnit = goodsUnitList.get(i);
                if (usedMap.containsKey(goodsUnit.getUnitId())) {
                    GoodsUnitVo goodsUnitVo = usedMap.get(goodsUnit.getUnitId());
                    if (goodsUnit.getTimes().doubleValue() != goodsUnitVo.getTimes().doubleValue()) {
                        String times = "";
                        if (Utils.isInt(goodsUnitVo.getTimes())) {
                            times = goodsUnitVo.getTimes().intValue()+"";
                        } else {
                            times = PdosUtils.getNumber(goodsUnitVo.getTimes(),businessSet);
                        }
                        responseEntity = ResponseEntity.fail("单位："+goodsUnitVo.getUnit().getName()+",已被业务使用，换算倍数"+times+"不能修改");
                        break;
                    }
                }
            }
            if (responseEntity != null) {
                return responseEntity;
            }
        }

        return null;
    }

    private ResponseEntity checkUploadUnit(Company company, GoodsVo goodsVo){
        //开启了多单位，需要检查不能有重复的单位； 同时检查换算倍数 必须>1切<=1000
        List<GoodsUnit> goodsUnitList = goodsVo.getGoodsUnitList();

        ResponseEntity responseEntity = null;
        Map<String,GoodsUnit> map = new HashMap<>();
        List<String> codeList = new ArrayList<>();
        for (int i=0;i<goodsUnitList.size();i++) {
            GoodsUnit goodsUnit = goodsUnitList.get(i);
            if (map.containsKey(goodsUnit.getUnitId())) {
                //若存在表示有重复的单位
                responseEntity = ResponseEntity.fail("您已开启多单位，但是存在重复的单位，请修改");
                break;
            }
            if (!goodsUnit.getBase() && (goodsUnit.getTimes().doubleValue() <=1 || goodsUnit.getTimes().doubleValue() > 1000)) {
                responseEntity = ResponseEntity.fail("换算倍数必须为1到1000之间，且不能等于1,请修改");
                break;
            }
            map.put(goodsUnit.getUnitId(), goodsUnit);

            if (!Utils.isEmpty(goodsUnit.getCode())) {
                codeList.add(goodsUnit.getCode());
            }
        }

        //检查条码是否有被使用过的
        if (!Utils.isEmpty(codeList)) {
            Long count = goodsService.checkCodeListBeUsed(company.getId(), goodsVo.getId(), codeList);
            if (count > 0) {
                responseEntity = ResponseEntity.fail("条码已被使用，请修改");
            }
        }

        return responseEntity;
    }

    private ResponseEntity checkUploadSn(boolean hasStock, Goods goods, List<GoodsSn> goodsSnList){


        if (!Utils.isEmpty(goodsSnList)){
            //检查库存和sn号是否对应
            List<GoodsStock> stockList = goodsStockService.listByGoods(goods.getId());

            Map<String,Integer> map = new HashMap<>();//houseId,count
            for (GoodsSn goodsSn : goodsSnList) {
                if (!map.containsKey(goodsSn.getHouseId())){
                    map.put(goodsSn.getHouseId(), 1);
                } else {
                    map.put(goodsSn.getHouseId(), map.get(goodsSn.getHouseId())+1);
                }
            }

            ResponseEntity responseEntity = null;
            for (int i=0; i<stockList.size(); i++){
                GoodsStock goodsStock = stockList.get(i);
                if (goodsStock.getNum().doubleValue() > 0) {
                    //库存大于0的，要检查其sn对应的数量
                    if (!map.containsKey(goodsStock.getHouseId()) || goodsStock.getNum().doubleValue()!=map.get(goodsStock.getHouseId())) {
                        //有库存的，但是没有sn；或者sn数量与库存数量不一致
                        responseEntity = ResponseEntity.fail("序列号数量与库存数量不一致，不允许开启序列号");
                        break;
                    }
                }
            }
            if (responseEntity != null) {
                return ResponseEntity.fail("序列号数量与库存数量不一致，不允许开启序列号");
            }
        } else {
            if (hasStock) {
                return ResponseEntity.fail("序列号数量与库存数量不一致，不允许开启序列号");
            }
        }
        return null;
    }
}
